<template>
  <el-card>
    <div slot="header">
      <div>
        <span>检查记录：</span>
        <span style="font-weight: bold">{{ record.clientName }}</span>
      </div>
      <div :span="24" style="padding-top:7px;margin-top:5px;border-top:1px solid #ddd">
        <el-tag style="margin: 0 2px" type="danger" size="small">
          <i class="el-icon-time"></i>
          {{ duration }}
        </el-tag>
        <el-tag
          v-for="(item, index) in clientInfo"
          :key="index"
          style="margin: 0 2px"
          size="small"
          >{{ item }}</el-tag
        >
      </div>
    </div>
    <el-form label-width="100px">
      <el-form-item
        v-for="(category, index) in formData"
        :key="index"
        :label="category.title"
      >
        <el-radio-group
          v-model="category.value"
          @change="handleChange"
          v-if="false"
        >
          <el-radio-button
            v-for="(text, idx) in valueTexts"
            :key="idx"
            :label="idx"
            >{{ text }}</el-radio-button
          >
        </el-radio-group>
        <el-select
          v-model="category.value"
          @change="handleChange"
          placeholder="请选择"
          style="width: 100%"
        >
          <el-option
            v-for="(text, idx) in valueTexts"
            :key="idx"
            :label="text"
            :value="idx"
          >
          </el-option>
        </el-select>
        <el-collapse-transition>
          <div v-if="category.value > 0">
            <div>
              <i class="el-icon-caret-bottom"></i>
              请选择或输入
              <b>&nbsp;{{ category.title }}&nbsp;</b>中表现出
              <b>&nbsp;{{ valueTexts[category.value] }}&nbsp;</b>的项目
              <span v-if="category.value > 0 && category.value < 3">
                <b>（必填）</b>
              </span>
              <span v-else>（选填）</span>
            </div>
            <el-select
              v-model="category.remark"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择或直接输入"
              style="width: 100%"
            >
              <el-option
                v-for="item in category.items"
                :key="item.title"
                :label="item.title"
                :value="item.title"
              ></el-option>
            </el-select>
            <div>
              <i class="el-icon-caret-bottom"></i>
              请描述
              <b>&nbsp;{{ category.title }}&nbsp;</b>评分为
              <b>&nbsp;{{ valueTexts[category.value] }}&nbsp;</b>的具体原因
              <span v-if="category.value > 0 && category.value < 3">
                <b>（必填）</b>
              </span>
              <span v-else>（选填）</span>
            </div>
            <el-input
              type="textarea"
              resize="none"
              :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="请输入原因"
              v-model="category.comment"
              @change="handleChange"
            ></el-input>
          </div>
        </el-collapse-transition>
      </el-form-item>
      <el-divider></el-divider>
      <el-form-item label="提交选项">
        <el-radio-group v-model="level">
          <el-radio-button label="一般">作为一般记录</el-radio-button>
          <el-radio-button label="案例">作为案例记录</el-radio-button>
          <el-radio-button label="范例">作为范例记录</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-divider></el-divider>
    </el-form>
    <div style="text-align: center; padding-top: 24px">
      <ConfirmSubmit @submit="handleSubmit" />
      <ConfirmDispose @dispose="handleDispose" />
    </div>
  </el-card>
</template>

<script>
import ConfirmSubmit from "./ConfirmSubmit";
import ConfirmDispose from "./ConfirmDispose";
export default {
  props: {
    recID: {
      type: Number,
      required: true,
    },
  },
  components: {
    ConfirmSubmit,
    ConfirmDispose,
  },
  data() {
    return {
      activeNames: [],
      duration: "--'--\"",
      durationVal: 0,
      formData: [],
      remark: "",
      showRmk: {},
      valueTexts: ["未涉及", "缺陷", "不足", "合格", "良好", "优秀"],
      commentValues: [1, 2, 5],
      level: "一般",
    };
  },
  computed: {
    record() {
      return this.$store.state.record.inspect.liveRecord[this.recID];
    },
    clientInfo() {
      return [
        this.record.clientOffice,
        this.record.clientGroup,
        this.record.clientRank,
        this.record.seat,
        this.record.sector ? this.record.sector : "-",
      ];
    },
    userInfo() {
      return this.$store.state.login.userinfo;
      // return this.$store.getters.userbase;
    },
  },
  methods: {
    countValue(idx) {
      let items = this.formData[idx].items;
      if (!items) {
        return "（已填：0，总共：0）";
      }
      let c = 0;
      for (let i = 0; i < items.length; i++)
        if (items[i].value > 0) {
          c++;
        }
      return "（已填：" + c + "，总共：" + items.length + "）";
    },
    handleDispose(idx = this.recID) {
      this.$store.commit("record/disposeLiveInspect", { idx });
      this.$emit("dispose", this.recID);
    },
    handlePrepare() {
      let content = JSON.parse(JSON.stringify(this.record));
      let begin = new Date(content.begin);
      let beginStr = "";
      beginStr += begin.toLocaleDateString().replace(/\//g, "-");
      beginStr +=
        " " +
        begin.getHours() +
        ":" +
        begin.getMinutes() +
        ":" +
        begin.getSeconds();
      content.begin = beginStr;
      // let time = new Date();
      let time = new Date();
      time.setTime(begin.getTime() + this.durationVal);
      let timeStr = "";
      timeStr += time.toLocaleDateString().replace(/\//g, "-");
      timeStr +=
        " " +
        time.getHours() +
        ":" +
        time.getMinutes() +
        ":" +
        time.getSeconds();
      content.time = timeStr;
      content.duration = parseInt((time.getTime() - begin.getTime()) / 60000);
      content.userName = this.userInfo.name;
      content.userGroup = this.userInfo.clientGroup;
      content.userOffice = this.userInfo.clientOffice;
      content.level = this.level;
      content.type = "现场";
      return content;
    },
    handleCheck(content) {
      let count = 0;
      for (let i = 0; i < content.categories.length; i++) {
        if (content.categories[i].value > 0) {
          if (content.categories[i].value < 3) {
            if (content.categories[i].comment.length === 0) {
              this.$notify.error({
                title: "缺少必填项",
                message:
                  "请您选择导致【" +
                  content.categories[i].title +
                  "】项评分为【" +
                  this.valueTexts[content.categories[i].value] +
                  "】的项目",
              });
              return null;
            } else if (content.categories[i].comment.length === 0) {
              this.$notify.error({
                title: "缺少必填项",
                message:
                  "请您填写【" +
                  content.categories[i].title +
                  "】项评分为【" +
                  this.valueTexts[content.categories[i].value] +
                  "】的原因",
              });
              return null;
            }
          }
          count++;
          delete content.categories[i].items;
        } else {
          content.categories.splice(i, 1);
          i--;
        }
      }
      if (count == 0) {
        this.$notify.warning({
          title: "未提交",
          message: "请先完成至少一个检查项",
        });
        return null;
      }
      return { content, count };
    },
    handleUpload({ content, count }) {
      this.axios
        .post("api/create_inspect_record/", {
          user: this.$store.state.login.userbase,
          data: content,
        })
        .then((response) => {
          if (response.data.status === 0) {
            this.$notify.success({
              title: "提交成功",
              message:
                "已经为" + content.clientName + "提交了" + count + "条检查项目",
            });
            this.handleDispose();
            return true;
            // return response.data.status;
          } else if (response.data.status === 1) {
            this.$notify.error({
              title: "用户验证错误",
              message: "请您将记录内容进行纸质保存，重新登录后再试",
            });
            // return response.data.status;
          } else {
            this.$notify.error({
              title: "未知错误",
              message: "请您将记录内容进行纸质保存",
            });
            this.$notify.info({
              title: "错误信息",
              message: JSON.stringify(response.data),
            });
            console.log(JSON.stringify(response.data));
            // return -1;
          }
        })
        .catch((exception) => {
          console.log(JSON.stringify(exception));
        });
      return false;
    },
    handleSubmit() {
      this.handleChange();
      this.handleUpload(this.handleCheck(this.handlePrepare()));
    },

    handleChange() {
      this.$store.commit("record/saveLiveInspect", {
        idx: this.recID,
        content: this.formData,
      });
    },
    handleAdd(idx, remark) {
      if (remark.length == 0) return;
      if (!this.formData[idx].items) this.formData[idx].items = [];
      this.formData[idx].items.push({
        title: "其他",
        subtitle: "",
        value: 0,
        remark: remark,
        comment: "",
      });
      this.remark = "";
      this.handleChange;
      this.showRmk[idx] = false;
    },
    handleCollapse() {},
    calcDuration() {
      this.durationVal = new Date().getTime() - this.record.begin;
      let duration = Math.round(this.durationVal / 1000);
      this.duration = parseInt(duration / 60) + "'" + (duration % 60) + '"';
    },
  },
  created() {
    this.formData = JSON.parse(JSON.stringify(this.record.categories));
    // if in present
    if (this.record.recordType === 0) {
      // timer.create
      let self = this;
      const timer = setInterval(() => {
        self.calcDuration();
      }, 1000);
      // timer.dispose
      this.$once("hook:beforeDestroy", () => {
        clearInterval(timer);
      });
    } else if (this.record.recordType === 1) {
      this.durationVal = this.record.duration * 60 * 1000;
      this.duration = this.record.duration + "'00" + '"';
    }
  },
};
</script>
